package com.h2cloud.ReactorTest.reactor.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Package: com.h2cloud.ReactorTest.reactor.server
 * @ClassName: Handler
 * @Author: wulongkai
 * @CreateTime: 2024/7/23 15:53
 * @Description:
 */
public class Handler implements Runnable {

    private final SocketChannel clientSocketChannel;

    public Handler(SocketChannel clientSocketChannel) {
        this.clientSocketChannel = clientSocketChannel;
    }

    @Override
    public void run() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        try {
            System.out.println("Handler " + clientSocketChannel.getRemoteAddress());
            // 模拟处理时长
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 读取数据
            int read = clientSocketChannel.read(byteBuffer);
            if (read <= 0) {
                clientSocketChannel.close();
            } else {
                System.out.println(new String(byteBuffer.array()));
            }
            System.out.println("处理完成-" + clientSocketChannel.getRemoteAddress());
        } catch (IOException e1) {
            try {
                clientSocketChannel.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            e1.printStackTrace();
        }
    }

}

